package apis

import (
	"github.com/gin-gonic/gin"
	"fmt"
	"net/http"
	"strings"
	"hulk-api/models/server/asset"
	"hulk-api/models/server/db"
	"io/ioutil"
	"hulk-api/util"
	"log"
)

func GetAssets(c *gin.Context) {
	assets,_ := asset.GetAssets()
	c.JSON(http.StatusOK,gin.H{
		"code": 200,
		"assets": assets,
	})

}

//sql 数据库列表
func GetDbList(c *gin.Context) {
	dblist,_ := db.GetDbList()
	c.JSON(http.StatusOK,gin.H{
		"code": 200,
		"dblist": dblist,
	})
}

//sql 任务管理
func GetSqlJobList(c *gin.Context) {
	var job db.Job
	//c.Bind(&job)   //TODO：ROLE 鉴权
	job.Dbname = c.Query("dbname")
	jobs := job.GetBrotherJobs().UndealJobs().SuccessJobs().FailedJobs()

	c.JSON(http.StatusOK,gin.H{
		"code": 200,
		"jobs": jobs,

	})
}



func GetDbListByInstance(c *gin.Context) {
	var database db.Db
	database.Instance = c.Query("instance")
	dblist,_ := database.GetDbListByInstance()
	c.JSON(http.StatusOK,gin.H{
		"code": 200,
		"dblist": dblist,
	})
}


//sql任务执行结果-拒绝执行
func RejectDbJob(c *gin.Context) {
	var job db.Job
	c.BindJSON(&job)   //TODO：ROLE 鉴权
	job.UpdateStatus()
	c.JSON(http.StatusOK,gin.H{
		"code": 200,
	})
}

//func AddDbJob(c *gin.Context) {
//	var job db.Job
//	c.BindJSON(&job)   //TODO：ROLE 鉴权
//
//	job.AddSqlJob()
//	c.JSON(http.StatusOK,gin.H{
//		"code": 200,
//	})
//}

func AddDbJob(c *gin.Context) {

	file,_,err := c.Request.FormFile("file")
	if err != nil { //测试报告
		if err.Error() == "http: no such file" { //todo:寻求更好的解决方案，先走需求
			job := db.Job{
				Dbname: c.Request.Form.Get("dbname"),
				SqlType: c.Request.Form.Get("type"),
			}
			job.AddSqlJob(c.Request.Form.Get("statement"))
			c.JSON(http.StatusOK,gin.H{
				"code": 200,
			})
			return


		}else {
			c.String(http.StatusBadRequest,fmt.Sprintf("get file err : %s", err.Error()))
			return
		}

	}

	//fmt.Println(file,header)

	job := db.Job{
		Dbname: c.Request.Form.Get("dbname"),
		SqlType: c.Request.Form.Get("type"),
	}

	buf ,err := ioutil.ReadAll(file)
	isUtf8 := util.ValidUTF8(buf)
	//fmt.Println("string buff ",buf)
	if !isUtf8 {
		c.JSON(http.StatusOK,gin.H{
			"code": 400,
			"message": "请上传utf-8格式文件",
		})
		return
	}

	job.AddSqlJob(string(buf))

	c.JSON(http.StatusOK,gin.H{
		"code": 200,
	})
}



//sql任务执行结果-确认执行
func ExecDbJob(c *gin.Context) {
	var job db.Job
	c.BindJSON(&job)   //TODO：ROLE 鉴权
	job.GetSqlJob().Do()
	c.JSON(http.StatusOK,gin.H{
			"code": 200,
		})

}

//数据库查询操作页面-表
func GetTables(c *gin.Context) {
	//c.BindJSON(&job)   //TODO：ROLE 鉴权
	var tables db.Tables
	tables.Instance = c.Query("instance")
	tables.Dbname = c.Query("dbname")
	tables.Show()
	c.JSON(http.StatusOK,gin.H{
		"code": 200,
		"tableList": tables.List,
	})
}

//数据库查询操作页面-查询操作


//数据库查询操作页面-批量查询
func ExecDbSelect(c *gin.Context) {
	var s db.Select
	c.BindJSON(&s)
	fmt.Println("statement... " , strings.Split(s.Statement,";"))
	selects := strings.Split(s.Statement,";")
	num := len(selects)
	var finalheader [][]string
	var finalresult [][]map[string]string

	for _,content := range selects {


		if strings.TrimSpace(content) == "" ||  len(strings.TrimSpace(content)) < 8 ||strings.ToLower(strings.TrimSpace(content)[0:6]) !="select" {
			log.Println("pass this sqlstatement " , content)
			continue
		}
		s.Statement = content
		headerList,result,err := s.Do()
		if err != nil {
			headerList = []string{"error"}
			//result = []map[string]string{map[string]string{"error":err.Error()}
			//result[0] = map[string]string{"error":err.Error()}
			result = append(result,map[string]string{"error":err.Error()})
		}


		finalheader = append(finalheader,headerList)
		finalresult = append(finalresult,result)
	}
	c.JSON(http.StatusOK,gin.H{
		"code": 200,
		"finalheader" : finalheader ,
		"finalresult": finalresult,
		"number" : num,
	})






}

//慢日志查詢頁面
func GetSlowLog(c *gin.Context) {
	var slog db.SlowLog

	slowlog,_ := slog.GetSlowLog()

	c.JSON(http.StatusOK,gin.H{
		"code": 200,
		"slowlog": slowlog,
	})

}